<template>
  <div class="page-body-div">
    <el-scrollbar :wrap-class="{ wrapClass: true }" class="dialog-scrollbar">
      <el-card class="box-card">
        <div style="height: 40px; text-align: center">
          {{ $t('email.createTemplate') }}
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-form-item :label="$t('email.templateName')" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('email.templateContent')"
            prop="templateContent"
          >
            <tinymce-page
              v-model="form.templateContent"
              ref="child"
            ></tinymce-page>
          </el-form-item>
          <div style="text-align: center">
            <el-button
              type="primary"
              style="width: 85%"
              v-loading.fullscreen.lock="fullscreenLoading"
              @click="handleSubmit('form')"
              plain
              >{{ $t('permission.confirm') }}</el-button
            >
          </div>
        </el-form>
        <div style="height: 100px"></div>
      </el-card>
    </el-scrollbar>
  </div>
</template>
<script>
import TinymcePage from '../Tinymce/index.vue'
import html2canvas from 'html2canvas'
import storage from '@/utils/storage'
import {
  getAction,
  postAction,
  getUrlAction,
  postUrlAction,
} from '@/api/common'
export default {
  name: 'baseform',
  props: {
    show: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    TinymcePage,
  },
  data: function () {
    return {
      fullscreenLoading: false,
      form: {
        Title: '',
        TemplateContent: '',
        Type: 1,
        Attribute: 1,
      },
      rules: {
        title: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.templateName')]),
            trigger: 'blur',
          },
        ],
        templateContent: [
          {
            required: true,
            message: this.$t('common.enter', [
              this.$t('email.templateContent'),
            ]),
            trigger: 'blur',
          },
        ],
      },
    }
  },
  watch: {},
  methods: {
    // 编辑和弹出的初始化页面
    init(id) {
      // console.log(echarts)
      // const chartDom = document.getElementById('charts')
      // const myChart = echarts.init(chartDom)
      // myChart.setOption(option)

      debugger
      this.form.id = id || ''
      // 显示弹出层
      // 编辑的时候回显
      this.$nextTick(() => {
        console.log('nextTick')
      })
    },
    handleSubmit(formName) {
      this.fullscreenLoading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          postAction(this.form, 'EmailTemplate/Create').then((res) => {
            if (res.code === 20000) {
              this.htmlToImage(res.data.id).then(() => {
                this.fullscreenLoading = false
                this.$message({
                  message: this.$t('email.createEDMTemplateSuccessfully'),
                  type: 'success',
                })
                this.$router.push('/email/emailTemplate/Index')
              })
            } else {
              this.fullscreenLoading = false
              this.$message({
                message: this.$t('email.createEDMTemplateFailed'),
                type: 'warning',
              })
            }
          })
        } else {
          this.fullscreenLoading = false
          this.$message({
            message: '参数不完整',
            type: 'warning',
          })
          console.log('error submit!!')
          return false
        }
        this.resetForm('form')
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleClick(tab, event) {
      console.log('handleClick')
    },
    handleChange(value) {
      console.log('handleChange')
    },
    htmlToImage(id) {
      const result = new Promise((resolve, reject) => {
        const element = this.$refs.child.getElementByIdInTinymce('tinymce')
        const width = 1490
        const height = 850
        const scale = 1
        const canvas = document.createElement('canvas')
        // 获取元素相对于视窗的偏移量
        // const rect = element.getBoundingClientRect()
        canvas.width = width * scale
        canvas.height = height * scale * 1
        const context = canvas.getContext('2d')
        if (context) {
          context.scale(scale, scale)
        }

        // 设置context位置, 值为相对于视窗的偏移量的负值, 实现图片复位
        const canvasHeight = window.scrollY
        if (context) {
          context.translate(0, -canvasHeight)
        }

        const options = {
          scale: scale,
          canvas: canvas,
          width: width,
          height: height,
          taintTest: true, // 在渲染前测试图片
          useCORS: true, // 貌似与跨域有关，但和allowTaint不能共存
          dpi: window.devicePixelRatio, // window.devicePixelRatio是设备像素比
          background: '#fff',
        }

        const res = html2canvas(element, options).then((canvas) => {
          const dataURL = canvas.toDataURL('image/png', 0.5) // 将图片转为base64, 0-1 表示清晰度
          const keyName = 'crm_email_template_id_' + id
          const dataURLV = this.compress(dataURL, 2, function (base64) {
            storage.set(keyName, base64)
          })
          resolve(dataURLV)
        })
      })
      return result
    },
    /* 压缩base64图片 */
    compress(
      base64, // 源图片
      rate, // 缩放比例
      callback // 回调
    ) {
      // 处理缩放，转格式
      const _img = new Image()
      const _this = this
      _img.onload = function () {
        const _canvas = document.createElement('canvas')
        const w = this.width / rate
        const h = this.height / rate
        _canvas.setAttribute('width', w)
        _canvas.setAttribute('height', h)
        _canvas.getContext('2d').drawImage(this, 0, 0, w, h)
        const base64 = _canvas.toDataURL('image/jpeg')
        _canvas.toBlob(function (blob) {
          if (blob.size > 20 * 1024) {
            // 如果还大，继续压缩
            _this.compress(base64, rate, callback)
          } else {
            callback(base64)
          }
        }, 'image/jpeg')
      }
      _img.src = base64
    },
  },
}
</script>

<style scoped>
.page-body-div {
  padding: 20px 30px;
  background-color: white;
}

.dialog-scrollbar {
  height: 870px;
}
</style>
